package leetcode;

public class MoveZeros {

	public static void main(String[] args) {
		int[] nums = { 0, 1, 0, 3, 12, 15, 26, 0, 0};
		MoveZeros moveZeros = new MoveZeros();
		moveZeros.moveZeroes2(nums);
		for (int i = 0; i < nums.length; i++) {
			System.out.print(nums[i] + " ");
		}
	}

	//Abosulutely, the algorthim is bad
	//a brilliant solution is we move the non zero element to the prefix, and then set last elenment to 0
	public void moveZeroes(int[] nums) {
		if (nums == null || nums.length == 0) {
			return;
		}
		boolean swap = false;
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] != 0) {
				continue;
			}
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[j] != 0) {
					swap(nums, i, j);
					swap = true;
					break;
				}
			}
			if(!swap){
				break;
			}
		}
	}
	public void swap(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	public void moveZeroes2(int[] nums){
		if(nums == null || nums.length <= 0){
			return;
		}
		int j = 0;
		for (int i = 0; i < nums.length; i++) {
			if(nums[i] != 0){
				nums[j++] = nums[i];
			}
		}
		for (;  j < nums.length; j++) {
			nums[j] = 0;
		}
	}
}
